package com.flycms.modules.user.controller;

import com.flycms.common.controller.BaseController;
import com.flycms.common.utils.result.Result;
import com.flycms.modules.shiro.AdminToken;
import com.flycms.modules.user.service.AdminService;
import com.flycms.modules.shiro.ShiroUtils;
import com.flycms.modules.site.service.SiteService;
import com.wf.captcha.utils.CaptchaUtil;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * Biz-Boot, All rights reserved
 * 版权：企业之家网 -- 企业建站管理系统<br/>
 * 开发公司：97560.com<br/>
 *
 * 登录、注册
 *
 * @author 孙开飞
 */
@Controller
public class AdminAccountController extends BaseController {
	@Resource
	private AdminService adminService;
	@Resource
	private SiteService siteService;

	// 登录
	@GetMapping(value = "/system/login{url.suffix}")
	public String login() {
		return "system/admin/login";
	}

	/**
	 * 登录
	 */
	@ResponseBody
	@PostMapping(value = "/system/login{url.suffix}")
	public Result login(String username, String password, String captcha) throws IllegalAccessException {
        if(StringUtils.isEmpty(captcha)){
            return failure(1,"验证码不能为空");
        }
		if (!CaptchaUtil.ver(captcha, request)) {
			CaptchaUtil.clear(request);  // 清除session中的验证码
			return failure(2,"验证码不正确");
		}
		try{
			Subject subject = ShiroUtils.getSubject();
			//UsernamePasswordToken token = new UsernamePasswordToken(username, password);
			UsernamePasswordToken token = new AdminToken(username, password);
			subject.login(token);
            return success("您登陆的是管理员账户","/admin/index");
		}catch (UnknownAccountException e) {
            return failure("账号不存在");
		}catch (LockedAccountException e) {
            return failure("账号已被锁定,请联系管理员");
		} catch (IncorrectCredentialsException e) {
            return failure("账号或密码不正确");
		}catch (AuthenticationException e) {
            return failure("账户验证失败");
		}
	}

	/**
	 * 退出
	 */
	@RequestMapping(value = "/system/logout{url.suffix}", method = RequestMethod.GET)
	public String logout() {
		ShiroUtils.logout();
		return "redirect:/system/login.do";
	}
}
